

import UIKit
import GradientLoadingBar
import Alamofire
import Reachability


class CompletionTabViewController: UIViewController {
    var myNavigationController: UINavigationController?
    var isFavorite = false
    var pageTitle: String = "创作"
    var tabList: [String] = []
    var list:[Completion] = []
    var completionSectionList: [CompletionSection] = []
    var  tabPageViewController: TabPageViewController!
    var currentPage = 1
    var total = 0
    // 懒加载
    let reachability = try! Reachability()
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
           return [NSAttributedString.Key.foregroundColor: UIColor.black]
       }
    
 
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = pageTitle
        getLocalJson()
        
        self.view.backgroundColor = commonDarkBackgroundColor
        reachability.whenReachable = { reachability in
            if reachability.connection == .wifi {
                print("Reachable via WiFi")
            } else {
                print("Reachable via Cellular")
            }
            if !self.isFavorite{
                self.getCompletionList()
            }
        }
        
        do {
            try reachability.startNotifier()
        } catch {
            print("Unable to start notifier")
        }
    }
    
    func getLocalJson(){
        let data = Data(StoreManager.getCompletionJson().utf8)
        do {
            
            let jsonDecoder = JSONDecoder()
            let completionResponse = try jsonDecoder.decode(CompletionResponse.self, from: data)
            
            let list = completionResponse.data
            
            parseSection(list: list)
        } catch {
            print("getLocalJson:\(error)")
        }
    }
    
    func getCompletionList(){
        let parameters = BasicPageParameters(page: currentPage)
        AFManager.sharedInstance.manager.request("\(baseUrl)creator/listV3",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
            if let string = response.value{
               
                
                let data = Data(string.utf8)
                do {
                    let jsonDecoder = JSONDecoder()
                    let completionListResponse = try jsonDecoder.decode(CompletionListResponse.self, from: data)
                    
                    let isLastPage = completionListResponse.data.isLastPage
                    self.total = completionListResponse.data.total
                    print("isLastPage=\(isLastPage)")
                    self.list = self.list + completionListResponse.data.list
                    
                    self.currentPage = self.currentPage + 1
                    if !isLastPage{
                        self.getCompletionList()
                    }else{
                        //最后一页处理总的数据
                        self.parseSection(list: self.list)
                        if !self.list.isEmpty , self.list.count == self.total{
                            //save to local
                            do {
                                let completionResponse = CompletionResponse(code: 200, data: self.list, message: "success")
                                let jsonEncoder = JSONEncoder()
                                let jsonData = try jsonEncoder.encode(completionResponse)
                                let json = String(data: jsonData, encoding: String.Encoding.utf8)
                                if let jsonString = json{
                                    StoreManager.setCompletionJson(json: jsonString)
                                }
                            } catch {
                                print(error)
                            }
                        }
                    }
                    
                } catch {
                    print(error)
                }
            }
        }
        
    }
    
    
    
    func parseSection(list:[Completion]){
        
        var completion: Completion?
        var index = -1
        self.completionSectionList = []
        self.tabList = []
        for assistant in list{
            if completion == nil || assistant.category != completion?.category{
                index = index + 1
                var completionSection = CompletionSection(data: [])
                completionSection.title = assistant.category
                self.tabList.append(assistant.category)
                self.completionSectionList.append(completionSection)
                completion = assistant
            }
            
            self.completionSectionList[index].data.append(assistant)
            
        }
        
        if tabPageViewController != nil{
            tabPageViewController.removeFromParent()
        }
        tabPageViewController = TabPageViewController()
        
        if tabPageViewController.tabItems.isEmpty{
            var index = 0
            tabPageViewController.isInfinity = false
            tabPageViewController.option.currentColor = .primaryColor
            tabPageViewController.option.defaultColor = UIColor(red: 129/255, green: 131/255, blue: 143/255, alpha: 1.0)
            tabPageViewController.option.pageBackgoundColor = commonBackgroundColor
            tabPageViewController.option.tabBackgroundColor = .white
            tabPageViewController.option.tabMargin = 16.0
            tabPageViewController.option.fontSize = 15
            
            for completionSection in completionSectionList{
                let vc = CompletionViewController()
                vc.isFavorite = self.isFavorite
                if myNavigationController != nil{
                    vc.myNavigationController = myNavigationController
                }else{
                    vc.myNavigationController = self.navigationController
                }
                
                vc.list = completionSectionList[index].data;
                tabPageViewController.tabItems.append((vc,completionSection.title))
                index += 1
            }
            self.view.addSubview(tabPageViewController.view)
            tabPageViewController.view.snp.makeConstraints { make in
                make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
                make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
                make.width.equalTo(self.view)
            }
        }
    }
    
}

